<?php

App::uses('AppController', 'Controller');

class IntelligenceController extends AppController
{
    public $bi = true;

    private function flattenArray2($object)
    {
        $keys = array_keys($object);
        $result = array();
        foreach ($keys as $key => $value)
        {
            if (is_array($object[$value]) === true)
            {
                $result = array_merge($result, $this->flattenArray2($object[$value]));
            }
            else
            {
                $result[$value] = $object[$value];
            }
        }
        return $result;
    }

    private function flattenArray($dataReport)
    {
        $result = array();
        foreach ($dataReport as $data)
        {
            $result[] = $this->flattenArray2($data);
        }
        return $result;
    }

    public function __call($name, $arguments)
    {
        $this->loadModel('Report');
        $report = $this->Report->findByAction($name);
        if (count($report) > 0)
        {
            $this->Report->query("SET lc_time_names = 'es_MX'");
            $dataReport = $this->Report->query($report['Report']['query']);
            $flattenData = $this->flattenArray($dataReport);
            $headers = array_keys($flattenData[0]);
            $this->set('headers', $headers);
            $this->set('dataReport', $flattenData);
            $this->set('title', $report['Report']['title']);
            $this->set('description', $report['Report']['description']);
            $this->view = 'index';
        }
        else
        {
            $request = array(
                'controller' => $this->name . "Controller",
                'action' => $this->request->params['action']
            );
            throw new MissingActionException($request);
        }
    }

}
